﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ScriptGenerator;
using System.Data.SqlServerCe;

namespace CEQuery
{
    public partial class ScriptGenerator : Form
    {
        public ScriptGenerator()
        {
            InitializeComponent();
        }
        public string ConnectionString { get; set; }
        public string TableName { get; set; }
        
        private void btnSelect_Click(object sender, EventArgs e)
        {
            saveFileDialog.Title = "Create the SQL CE / SQL Schema File";
            saveFileDialog.Filter = "SQL CE Schema Files (*.sqlce)|*.sqlce|SQL Schema Files (*.sql)|*.sql";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFile.Text = saveFileDialog.FileName;
            }
        }
        private bool ValidateInput()
        {
            bool isValid = true;
            if (this.txtFile.Text.Trim() == string.Empty)
            {
                isValid = false;
                errValidation.SetError(btnSelect, "Select a file.");
            }
            else
            {
                if (rdbSQLCE.Checked && !txtFile.Text.ToLower().EndsWith("ce"))
                    txtFile.Text += "ce";
                else if (rdbSQLServer.Checked && txtFile.Text.ToLower().EndsWith("ce"))
                    txtFile.Text = txtFile.Text.Substring(0, txtFile.Text.Length - 2);
                else
                    //NA
                errValidation.SetError(btnSelect, string.Empty);
            }


            if (chkTables.CheckedItems.Count == 0)
            {
                isValid = false;
                errValidation.SetError(grpTable, "Select at least one table.");
            }
            else
            {
                errValidation.SetError(grpTable, string.Empty);
            }
            return isValid;
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                List<string> tables = new List<string>();
                for (int index = 0; index < chkTables.CheckedIndices.Count; index++)
                {
                    tables.Add(chkTables.CheckedItems[index].ToString());                    
                }

                IRepository repository = new DBRepository(ConnectionString);

                Generator generator;
                generator = new Generator(repository, tables);
                //if(string.IsNullOrEmpty(TableName))
                //    generator = new Generator(repository);
                //else
                //    generator = new Generator(repository,TableName);

                // The execution below has to be in this sequence
                generator.GenerateTables(rdbSQLServer.Checked);
                if (rbWithData.Checked)
                {
                    generator.GenerateTableContent();
                }
                generator.GeneratePrimaryKeys();
                generator.GenerateUniqueKeys();
                generator.GenerateIndex();                
                generator.GenerateForeignKeys();

                Helper.WriteIntoFile(generator.GeneratedScript, txtFile.Text);
                Cursor.Current = Cursors.Default;
                btnHiddenOK.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void rdbSQLCE_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbSQLCE.Checked && !txtFile.Text.ToLower().EndsWith("ce"))
                txtFile.Text += "ce";
        }
        private void rdbSQLServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbSQLServer.Checked && txtFile.Text.ToLower().EndsWith("ce"))
                txtFile.Text = txtFile.Text.Substring(0,txtFile.Text.Length - 2);
        }
        private void ScriptGenerator_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TableName) && TableName != "ALL TABLE")
            {
                chkTables.Enabled = false;
                chkSelectAll.Visible = false;
                chkTables.Items.Add(TableName, true);
            }
            else
            {
                chkTables.Enabled = true;
                chkSelectAll.Visible = true;
                DataSet dsTable = new DataSet();
                using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
                {
                    using (SqlCeCommand cmd = new SqlCeCommand())
                    {
                        cmd.Connection = connection;
                        connection.Open();
                        cmd.CommandText = "SELECT table_name FROM information_schema.tables";
                        SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
                        da.Fill(dsTable);
                        connection.Close();
                    }
                }
                foreach (DataRow dr in dsTable.Tables[0].Rows)
                {
                    chkTables.Items.Add(dr[0].ToString(), false);
                }
                if (!string.IsNullOrEmpty(TableName) && TableName == "ALL TABLE")
                {
                    chkSelectAll.Checked = true;
                }
            }
        }
        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {            
            for (int index = 0; index < chkTables.Items.Count; index++)
            {
               chkTables.SetItemChecked(index,chkSelectAll.Checked);
            }
        }
        private void chkTables_SelectedValueChanged(object sender, EventArgs e)
        {
            bool isAllSelected = true;
            for (int index = 0; index < chkTables.Items.Count; index++)
            {
                if (!chkTables.GetItemChecked(index))
                {
                    isAllSelected = false;
                    chkSelectAll.CheckedChanged -= new EventHandler(chkSelectAll_CheckedChanged);
                    chkSelectAll.Checked = false;
                    chkSelectAll.CheckedChanged += new EventHandler(chkSelectAll_CheckedChanged);
                    break;
                }
            }
            if (isAllSelected)
            {
                chkSelectAll.Checked = true;
            }
        }
    }
}

